const depart = (http, dialog, api, appService) => {
	var service = {
		add: function(appScope) {
			appScope = appScope || this;
			var node = appScope.getTreeNode();
			// 新建根节点
			/*var id = node ? node.id : '';*/
			var id =  node.id;
			return api.form({
				title: '新建部门', 
				template: require('./views/form.tpl.html'), 
				name: 'org_depart_add',
				data: {
					parent_Id: id
				},
				beforeSettings: function() {
					var _scope = this;
					api.tree({
						scope: _scope,
						type: 'radio',
						url: 'basic/branch/selectedBranchTreeChecked',
						params: {
							depart_id: id
						},
						paths: []
					});
				},
				scope: {
					moveAdd: appService.moveAdd,
					moveRemove: appService.moveRemove
				},
				resolveWait: {
					roles: function() {
						return http.post('org_full_roles');
					}
				},
				resolveApplyScope: ['roles'],
				beforeSubmit: function(data) {
					var _scope = this;
					data.roleIds = (data.roles || []).map(function(role) {
						return role.id;
					});
					data.roles = null;
					delete data.roles;
					
					data.branchId = api.getTreeChecked(_scope.tree).map(function(node) {
						return node.id
					})[0];
				}
			}).then(function() {
				appScope.treeReload();
			});
		},
		edit: function(appScope, id) {
			appScope = appScope || this;
			if (id == null) {
				var node = appScope.getTreeNode();
				id = node.id;
				if (id == 'root') return;
			}
			
			return api.form({
				title: '编辑部门', 
				template: require('./views/form.tpl.html'), 
				name: 'org_depart_edit',
				beforeSettings: function() {
					var _scope = this;
					api.tree({
						scope: _scope,
						type: 'radio',
						url: 'basic/branch/selectedBranchTreeChecked',
						params: {
							depart_id: id
						},
						paths: []
					});
				},
				scope: {
					moveAdd: appService.moveAdd,
					moveRemove: appService.moveRemove
				},
				resolveWait: {
					roles: function() {
						return http.post({
						name:'org_depart_remaining_roles',
						params:{
							id:id
						}
					});
					},
					item: function() {
						// 获取单个部门数据
						return http.post({
							name: 'org_depart',
							params: {
								id: id
							}
						})
					}
				},
				resolveApplyScope: ['roles'], 
				resolveApplyData: ['item'],
				beforeSubmit: function(data) {
					var _scope = this;
					data.roleIds = (data.roles || []).map(function(role) {
						return role.id;
					});
					data.roles = null;
					delete data.roles;
					
					data.branchId = api.getTreeChecked(_scope.tree).map(function(node){
						return node.id;
					})[0];

				}
			}).then(function() {
				appScope.treeReload();
			});
		},
		remove: function(appScope, ids) {
			appScope = appScope || this;
			if (ids == null) {
				var node = appScope.getTreeNode();
				var id = node.id;
				if (id == 'root') return;
				ids = [id];
			}

			dialog.confirm('确定要删除' + (ids.length > 1 ? '这些' : '当前') + '部门？').result.then(function(r) {
				if (r) {
					http.post({
						name: 'org_depart_remove',
						params: {
							ids: ids
						},
						success: function() {
							appScope.treeReload();
						}
					})
				}
			});
		},
		select: function(categoryId) {
			var loadUserData = function(_scope, params) {
				_scope = _scope || this;
				var node = _scope.selectedTreeNode;
				if (!node) {
					return;
				}
				params = params || {};
				angular.extend(params, {
					id: node.id , 
					type : 1,
                    categoryId: categoryId
				});
				return api.gridLoad({
					name: 'org_branch_userList',
					params: params,
					scope: _scope
				});
			};
			var columns = [{
				name: '用户名',
				width: 200,
				field: 'username'
			}, {
				name: '真实姓名',
				width: 200,
				field: 'realname'
			}, {
				name: '注册时间',
				width: 200,
				field: 'crtime'
			}];
			return api.form({
				title: '选择用户',
				template: require('./views/form_select.tpl.html'),
				name: 'org_user_batchInfo',
				beforeSettings: function() {
					var _scope = this;
					api.tree({
						scope: _scope,
						type: 'tree',
						url: 'basic/branch/treeBranch'
					});
					_scope.changeNode = function(node) {
						_scope.selectedTreeNode = node;
						_scope.query();
					}
				},
				beforeSubmit: function(params, deferred) {
					var _scope = this;
					var data = _scope.gridBufferOptions.data || [];
					var ids = data.map(function(r) {
						return r.id;
					});
					if (ids.length === 0) {
						dialog.alert('请选取需要导入的数据！');
						return false;
					}
					params.ids = ids;
				},
				scope: {
					q: {},
					query: function(resetPage) {
						var _scope = this;
						if (resetPage === false || _scope.gridOptions.paginationCurrentPage == 1) {
							loadUserData(_scope, _scope.q);
						} else {
							api.gridReset(null, _scope);
						}
					},
					hasSelectedRecords: function(apiName) {
						return api.hasGridSelectedRecords(this, apiName);
					},
					gridOptions: {
						paginationCurrentPage: api.page.pageNumber,
						paginationPageSize: api.page.pageSize,
						useExternalPagination: true,
						columns: columns,
						forceFit: false,
						onRegisterApi: function(api, grid) {
							var _scope = grid.appScope;
							_scope.api = api;

							api.pagination && api.pagination.on.paginationChanged(_scope, function(newPage, pageSize) {
								_scope.query(false);
							});
						}
					},
					add: function() {
						var _scope = this;
						var rs = api.getGridSelectedRecords(_scope);
						var _data = _scope.gridBufferOptions.data || [];
						var ids = _data.map(function(_r) {
							return _r.id;
						});
						var data = [];
						rs.forEach(function(r) {
							var id = r.id;
							if (ids.indexOf(id) === -1) {
								if (r.$$hashKey) {
									delete r.$$hashKey;
								}
								data.push(r);
							}
						});
						_scope.gridBufferOptions.data = [].concat(_data, data);
					},
					remove: function() {
						var _scope = this;
						var data = _scope.gridBufferOptions.data || [];
						var rs = api.getGridSelectedRecords(_scope, 'bufferApi');
						rs.forEach(function(r) {
							var id = r.id,
								i;
							var ids = data.map(function(_r) {
								return _r.id;
							});
							if ((i = ids.indexOf(id)) !== -1) {
								data.splice(i, 1);
								_scope.bufferApi.selections.removeKey(id);
								_scope.bufferApi.grid.selection.selectedCount--;
							}
						});
					},
					gridBufferOptions: {
						columns: columns,
						forceFit: false,
						onRegisterApi: function(bufferApi, grid) {
							var _scope = grid.appScope;
							_scope.bufferApi = bufferApi;
						}
					}
				},
				config: {
					windowClass: 'x-window x-window-selection',
					width: '60%'
				}
			});
		}
	};
	return service;
}
depart.$inject = ['ui.http', 'ui.dialog', 'ui.api', 'OrgService'];

export default depart;